package common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import model.exceptions.InvalidNameException;

/**
 * Simple persistence help saving and loading files.
 * 
 * @author Paula Chen
 * 
 */
public enum Persistence
{
  INSTANCE;

  final public static String filesPath = "files";
  private static final String separator = System.getProperty("file.separator");

  /**
   * Serialize the object and save it to disk.
   * 
   * @param object
   *          the object that is being saved name the name of the file stored
   * 
   * @return a result, whose status indicates whether the operation succeeded.
   * 
   *         {@pre object != null, name != empty, name != null}
   * 
   * @throws InvalidNameException
   *           if the name was invalid IOException if file not found
   */
  public static Result save(Object object, String name) throws IOException, InvalidNameException
  {
    if (object == null)
    {
      return new Result(false, "Null object.");
    }
    if (name == "" || name == null)
    {
      throw new InvalidNameException("Null/Empty name.");
    }
    File file = new File(filesPath + separator + name + ".ser");
    new File(file.getParent()).mkdirs();

    BufferedOutputStream outFile = new BufferedOutputStream(new FileOutputStream(file));

    ObjectOutputStream output = new ObjectOutputStream(outFile);
    output.writeObject(object);
    output.close();
    return new Result(true);
  }

  /**
   * Load a file from disk and unserialize the object.
   * 
   * @param name
   *          the name of the file attempt to load
   * 
   * @return a result, whose status indicates whether the operation succeeded.
   * 
   *         {@pre name != empty, name != null}
   * 
   * @throws InvalidNameException
   *           if the name was invalid ClassNotFoundException if file not found
   */
  public static Object load(String name) throws InvalidNameException, ClassNotFoundException,
      IOException
  {
    if (name == "" || name == null)
    {
      throw new InvalidNameException("Null/Empty name.");
    }
    BufferedInputStream inFile;
    ObjectInputStream input;
    Object object;
    inFile = new BufferedInputStream(new FileInputStream(filesPath + separator + name + ".ser"));
    input = new ObjectInputStream(inFile);
    object = input.readObject();
    input.close();
    return object;
  }
}
